<template>
<pageTabelLayout>
  <template #pageHeader>
  <div class="search-form isheader">
    <div>
      <a-form size="mini" :model="sheetData" layout="inline">
        <!-- <CorporateSectorCascader :configCascader="configCascader" @changeCascader="changeCascader" /> -->
        <!-- <a-form-item label="所属仓库">
          <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" placeholder="" v-model="sheetData.warehouseId"
            allow-clear>
            <a-option v-for="(item, index) in warehouseList" :value="item.id" :key="index">
              {{ item.warehouseName }}
            </a-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="盘点单号">
          <a-input class="bacClass" :style="{ width: '10rem' }" v-model="sheetData.code" allow-clear></a-input>
        </a-form-item>
      </a-form>
    </div>
    <div>
      <Toolbar :items="['查询', '创建盘点单', '审核', '终止盘点']" @select="queryHandler" @init="initInventory"
        @audit="auditInventorySheet" @cel="delInventories">
      </Toolbar>
    </div>
  </div>
  <div class="my-divisders">
    <a-divider orientation="center">
      <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
      <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
    </a-divider>
  </div>
</template>
<template #pageTabel>
    <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"  :suppressDragLeaveHidesColumns="true" @grid-ready="sheetGridReady" style="height: calc(100% - 45px);"
    @columnResized="onColumnResized" @columnMoved="onColumnMoved"  @columnVisible="onColumnVisible"
      :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="sheetList" :columnDefs="sheetColDefs"
      :localeText="localeText1"></AgGridVuesCopys>
    <paginationCopys :page-size-options="pagingList1" :total="sheetData.total" show-total show-jumper show-page-size
      @change="pageChange" style="justify-content: center" :page-size="sheetData.size" :current="sheetData.current"
      @page-size-change="change" />
    </template>

  <!-- 盘点 -->
  <a-drawer :drawer-style="{ zIndex: 9999 }" height="100%" unmountOnClose :visible="pageData.showAdd"
    :mask-closable="false" placement="bottom" @cancel="pageData.showAdd = false" title="盘点"
    @ok="pageData.showAdd = false">
    <div class="search-form isheader">
      <a-form size="mini" :model="sheetData" layout="inline">
        <a-form-item label="原料名称">
          <a-input class="bacClass" :style="{ width: '10rem' }" v-model="sheetData.materialName" allow-clear></a-input>
        </a-form-item>
        <a-form-item label="纱批">
          <a-input class="bacClass" :style="{ width: '10rem' }" v-model="sheetData.yarnBatch" allow-clear></a-input>
        </a-form-item>
        <a-form-item v-if="tabKey == 2" label="机台号">
          <a-input class="bacClass" :style="{ width: '10rem' }" v-model="sheetData.machineCode" allow-clear></a-input>
        </a-form-item>
      </a-form>
      <Toolbar :items="toolbarList" @select="selectHandle" @export="detailExport" @import="detailImport"
        @add="addHandler" @saveData="sideOk"></Toolbar>
    </div>
    <a-tabs   :lazy-load="true" type="card" :justify="true" :active-key="tabKey" @change="tabChange" style="height:95%;">
      <a-tab-pane title="盘点汇总" :key="1">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" @grid-ready="gridReady1" style="height: 93%"
          :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="summaryList" :columnDefs="summaryColDefs"
          :localeText="localeText1"></AgGridVuesCopys>
        <paginationCopys :page-size-options="pagingList1" :total="sheetData.total" show-total show-jumper show-page-size
          @change="pageChange1" style="justify-content: center;margin-top: 10px;" :page-size="sheetData.size"
          :current="sheetData.current" @page-size-change="change1" />
      </a-tab-pane>
      <a-tab-pane title="盘点明细" :key="2">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" @grid-ready="gridReady2" style="height: 93%"
          :defaultColDef="defaultColDef1" class="ag-theme-alpine" :rowData="detailList" :columnDefs="detailColDefs"
          :localeText="localeText1"></AgGridVuesCopys>
        <paginationCopys :page-size-options="pagingList1" :total="sheetData.total" show-total show-jumper show-page-size
          @change="pageChange2" style="justify-content: center;margin-top: 10px;" :page-size="sheetData.size"
          :current="sheetData.current" @page-size-change="change2" />
      </a-tab-pane>
    </a-tabs>
  </a-drawer>
  <!-- 盘点明细 -->
  <a-drawer :drawer-style="{ zIndex: 9999 }" height="70%" unmountOnClose :visible="pageData.childData"
    :mask-closable="false" placement="bottom" @cancel="pageData.childData = false" title="详情"
    @ok="pageData.childData = false" hide-cancel ok-text="关闭">
    <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" @grid-ready="gridReady3" style="height: 93%"
      :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="childList" :columnDefs="detailColDefs"
      :localeText="localeText1"></AgGridVuesCopys>
    <paginationCopys :page-size-options="pagingList1" :total="child.total" show-total show-jumper show-page-size
      @change="pageChange3" style="justify-content: center;margin-top: 5px;" :page-size="child.size"
      :current="child.current" @page-size-change="change3" />
  </a-drawer>
</pageTabelLayout>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { post, get } from '@/api/http'
import { localeText } from '@/api/aggridZw'

import Toolbar from '@/components/Toolbar.vue'
import { Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { ElMessage, ElMessageBox } from 'element-plus'
import { pagingList } from '@/api/paging'
import filedownload from 'js-file-download'
import WHService from '@/service/wh'
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import { log } from 'echarts/types/src/util/log'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
const pagingList1: any = ref(pagingList)
const headerShow = ref(true)
const auditStatus = ref(1)
const localeText1: any = ref(localeText)
const inventoryColDefs = ref<any>([])
const visible = ref(false)
const qrCodeImg = ref<any>()
const tabKey = ref(1)
const toolbarList: any = ref(['查询'])

const pageData = reactive({
  showAdd: false,
  showDetails: false,
  isShow: false,
  rHeight: 0,
  pageLoading: false,
  childData: false
})

const searchData = reactive<any>({
  id: null,
  companyId: null,
  code: '',
  warehouseType: null,
  total: 10,
  current: 1,
  size: 10,
});

const sheetData = reactive({
  companyId: null,
  companyName: null,
  warehouseId: '',
  code: '',
  warehouseType: null,
  machineCode: '',
  materialName: '',
  yarnBatch: '',
  total: 10,
  current: 1,
  size: 10,
});
const child = reactive({
  total: 10,
  current: 1,
  size: 10,
});
const firstSheetRow = reactive({
  id: null,
  warehouseType: null,
});

const warehouseList = ref([
  {
    warehouseName: '',
    warehouseTypeId: '',
    id: '',
  },
]);

//盘点单列表 查询
function sheetSelect() {
  post({
    url: '/wms/rawyarnInventoryDetail/findPagedInventorySheets',
    data: {
      code: sheetData.code,
      // warehouseId: sheetData.warehouseId,
      // companyId: sheetData.companyId,
      // warehouseType: 1,
      current: sheetData.current,
      size: sheetData.size,
    },
  }).then(({ code, data }) => {
    if (code === 200) {
      sheetList.value = data.records;
      sheetGridOptions.value.setRowData(data.records);
      sheetData.total = data.total;
      if (data.records.length > 0) {
        searchData.id = data.records[0].id;
        // searchData.warehouseType = data.records[0].warehouseType;
        auditStatus.value = data.records[0].status;
      }
    }
  })
};

//汇总 查询
function summarySelect() {
  post({
    url: '/wms/rawyarnInventoryDetail/findPagedInventorySum',
    data: {
      materialName: sheetData.materialName,
      yarnBatch: sheetData.yarnBatch,
      sheetId: dataList.id,
      // warehouseId: dataList.warehouseId,
      current: sheetData.current,
      size: sheetData.size
    }
  }).then(({ code, data }) => {
    if (code === 200) {
      summaryList.value = data.records;
      gridOption1.value.setRowData(data.records);
      sheetData.total = data.total;
    }
  })
};

//明细 查询
function detailSelect() {
  post({
    url: '/wms/rawyarnInventoryDetail/findPagedInventoryDetails',
    data: {
      materialName: sheetData.materialName,
      yarnBatch: sheetData.yarnBatch,
      machineCode: sheetData.machineCode,
      sheetId: dataList.id,
      current: sheetData.current,
      size: sheetData.size,
    },
  }).then(({ code, data }) => {
    if (code === 200) {
      detailList.value = data.records;
      gridOption2.value.setRowData(data.records);
      sheetData.total = data.total;
    }
  })
};

//详情 查询
let wlCode = ''
let records:any = {}
function childSelect() {
  post({
    url: '/wms/rawyarnInventoryDetail/findPagedInventoryDetails',
    data: {
      materialName: sheetData.materialName,
      yarnBatch: records.yarnBatch,
      brandName:records.brandName,
      customName:records.customName,
      colorCode:records.colorCode,
      colorName:records.colorName,
      machineCode: sheetData.machineCode,
      materialCode: wlCode,
      sheetId: dataList.id,
      current: child.current,
      size: child.size,
    },
  }).then(({ code, data }) => {
    if (code === 200) {
      childList.value = data.records;
      gridOption3.value.setRowData(data.records);
      child.total = data.total;
    }
  })
};

onMounted(() => {
  updateGridState01()
  sheetSelect()
  //获取公司信息
  post({
    url: '/wms/rawyarnInventoryDetail/fetchUserInfoByToken',
  }).then(({ code, data }) => {
    if (code === 200) {
      sheetData.companyId = data.firmId;
      sheetData.companyName = data.firmName;
      loadWarehouseList();
    }
  })
});

function queryHandler() {
  sheetData.current = 1;
  sheetSelect();
};

function selectHandle() {
  if (tabKey.value == 1) {
    sheetData.current = 1
    summarySelect();
  } else if (tabKey.value == 2) {
    sheetData.current = 1
    detailSelect();
  };
};

//盘点单列表
const sheetList = ref([])
const sheetGridOptions = ref();
const colState = ref()
function sheetGridReady(params: any) {
  sheetGridOptions.value = params.api;
  colState.value=params.columnApi
};
//盘点汇总
const summaryList = ref<any>([])
const gridOption1 = ref()
const gridReady1 = (params: any) => {
  gridOption1.value = params.api
}
//盘点明细
const detailList = ref<any>([])
const gridOption2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
};
//详情
const childList = ref<any>([])
const gridOption3 = ref()
const gridReady3 = (params: any) => {
  gridOption3.value = params.api
};
function pageChange(val: any) {
  sheetData.current = val
  sheetSelect()
};
function change(val: any) {
  sheetData.size = val
  sheetSelect()
}

function pageChange1(val: any) {
  sheetData.current = val
  summarySelect()
};
function change1(val: any) {
  sheetData.size = val
  summarySelect()
}

function pageChange2(val: any) {
  sheetData.current = val
  detailSelect()
};
function change2(val: any) {
  sheetData.size = val
  detailSelect()
}

function pageChange3(val: any) {
  child.current = val
  childSelect()
};
function change3(val: any) {
  child.size = val
  childSelect()
}

function tabChange(e: any) {
  tabKey.value = e
  sheetData.current = 1
  if (e == 1) {
    toolbarList.value = ['查询']
    summarySelect()
  } else if (e == 2) {
    toolbarList.value = ['查询', '新增','保存', '导入差异', '导出清单']
    detailSelect()
  }
};

function handleOk() {
  visible.value = false
};

function handleCancel() {
  visible.value = false
};

const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
};

const defaultColDef1 = {
  sortable: true,
  resizable: true,
  filter: true,
  editable: false
};

//盘点列表
const sheetColDefs = [
  {
    showRowGroup: 'hide_def',
    checkboxSelection: true,
    pinned: 'left',
    width: 290,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
  { headerName: '公司', field: 'companyName', width: 290 },
  { headerName: '盘点单号', field: 'code', width: 290 },
  {
    headerName: '状态',
    field: 'status',
    valueGetter: (params: any) => {
      switch (params.data.status) {
        case 1:
          return '未开始'
        case 2:
          return '进行中'
        case 3:
          return '已完成'
        case 4:
          return '已审核'
      }
    },
    width: 290
  },
  { headerName: '创建人', field: 'createUser', width: 290 },
  { headerName: '创建日期', field: 'createTime', width: 290 },
  {
    headerName: '操作',
    field: 'id',
    filter:false,
    cellRenderer: {
      template: `<a-button @click="a">盘点</a-button>`,
      setup(props: any) {
        const a = () => {
          DetailList(props.params.data)
        }
        return {
          a,
        }
      }
    },
    pinned: 'right',
    width: 155,
  },
];

//汇总列表
const summaryColDefs = [
  {
    showRowGroup: 'hide_def',
    checkboxSelection: true,
    pinned: 'left',
    width: 100,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
  { headerName: '客户', field: 'customName', width: 240 },
  { headerName: '原料编号', field: 'materialCode', width: 240 },
  { headerName: '原料名称', field: 'materialName', width: 240 },
  { headerName: '纱牌', field: 'brandName', width: 240 },
  { headerName: '纱批', field: 'yarnBatch', width: 242 },
  { headerName: '色号', field: 'colorCode', width: 242 },
  { headerName: '色称', field: 'colorName', width: 242 },
  { headerName: '重量', field: 'sumWeight', width: 242 },
  {
    headerName: '操作',
    field: 'id',
    filter:false,
    cellRenderer: {
      template: `<el-button @click="a" link style="color:#156dff">详情</el-button>`,
      setup(props: any) {
        const a = () => {
          wlCode = props.params.data.materialCode
          records = props.params.data
          childSelect()
          pageData.childData = true
        }
        return {
          a,
        }
      }
    },
    pinned: 'right',
    width: 150,
  },
]

//明细列表
let detailColDefs = [
  {
    showRowGroup: 'hide_def',
    checkboxSelection: true,
    pinned: 'left',
    width: 100,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
  { headerName: '客户', field: 'customName', width: 240,
    editable: (res: any) => {
      return res.data.editable ? true : false
    } },
  {
    headerName: '机台号', field: 'machineCode', key: 'machineCode', width: 184,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  }, // 覆盖了默认的不可编辑设置 },
  {
    headerName: '原料编号', field: 'materialCode', width: 184,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  },
  {
    headerName: '原料名称', field: 'materialName', width: 184,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  },
  {
    headerName: '纱牌', field: 'brandName', width: 183,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  },
  {
    headerName: '纱批', field: 'yarnBatch', width: 183,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  },
  {
    headerName: '色号', field: 'colorCode', width: 183,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  },
  {
    headerName: '色称', field: 'colorName', width: 183,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  },
  {
    headerName: '库存重量', field: 'totalWeight', width: 183,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  },
  {
    headerName: '实际重量', field: 'realWeight', width: 183,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  },
  {
    headerName: '差异重量', field: 'diffWeight', width: 183,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  },
  {
    headerName: '创建日期', field: 'createDate', width: 184,
    editable: (res: any) => {
      return res.data.editable ? true : false
    }
  },
];

// 公司下拉框
const whService = new WHService()
const fhWhList: any = whService.whList
const configCascader = ref<{}>({
  corporateWidth: '10rem', //公司宽度
  sectorWidth: '180px', //部门宽度
  corporateRquired: false, //公司是否必填
  sectorRquired: false, //部门是否必填
  size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
  corporateName: '选择公司', //公司label
  sectorName: '选择部门', //部门label
  cascaderShow: 'sector', //配置部门不显示
})
const changeCascader = (data: any) => {
  const { corporateId, sectorId, sectorLabel, corporateLabel } = data
  searchData.companyId = corporateId
}

//仓库下拉框
function loadWarehouseList() {
  post({
    url: 'wms/warehouse/getWarehouseByPara',
    data: { warehouseTypeId: 1, virtuallyState: 0 }
  }).then(({ code, data }) => {
    if (code === 200) {
      warehouseList.value = data;
    }
  })
};

function initInventory() {
  // if (sheetData.warehouseId == '') {
  //   Message.warning('请先选择仓库，再进行盘点初始化')
  //   return;
  // };
  // let wh: any = warehouseList.value.find((item) => item.id === sheetData.warehouseId)
  post({
    url: '/wms/rawyarnInventoryDetail/createRawyarnInventorySheet',
    data: {
      companyId: sheetData.companyId,
      companyName: sheetData.companyName,
      // warehouseId: sheetData.warehouseId,
      // warehouseName: wh.warehouseName,
      warehouseType: 1,
      fixed: 3
    },
  }).then(({ code, message }) => {
    if (code === 200) {
      if (message = '成功') {
        Message.success('创建成功');
        sheetSelect()
      }
    }else {
             Message.error({
               content: message,
               duration: 5000,
             })
    }
  })
};

//详情
const dataList: any = ref()
function DetailList(record: any) {
  for (let key in record) {
    dataList[key] = record[key]
  }
  if(tabKey.value == 1){
    summarySelect()
  }else{
    detailSelect()
  }
  pageData.showAdd = true
}

//保存
function sideOk() {
  let saveData = detailList.value.filter(d=>{ return d.id==undefined });
  for (let i = 0; i < saveData.length; i++) {
    if (saveData[i].machineCode==null || saveData[i].materialCode==null || saveData[i].materialName==null || saveData[i].totalWeight==null || saveData[i].realWeight==null ) {
      Message.error('机台号，原料编号，原料名称，库存重量，实际重量必填！')
      return;
    }
  }
  post({
        url: '/wms/rawyarnInventoryDetail/batchInsertRawyarnInventoryList',
        data: saveData
      }).then(({ code, data, message }: any) => {
        if (code === 200) {
          Message.success({
            content: '保存成功',
            duration: 5000,
          });
          sheetSelect();
        }
      })


}

const rows = ref([])
const auditInventorySheet = () => {
  let rows = sheetGridOptions.value.getSelectedRows()
  if (rows.length === 0) {
    Message.warning('请选择需要审核的盘点单！')
    return
  };
  if (rows[0].status != 3) {
    Message.warning('此盘点单盘点未完成或已审核，无法发起审核！')
    return
  };
  Modal.confirm({
    title: '系统提示',
    content: '确认审核此数据?',
    onOk() {
      post({
        url: '/wms/rawyarnInventoryDetail/auditInventorySheet',
        data: { id: rows[0].id },
      }).then(({ code, data, message }: any) => {
        if (code === 200) {
          Message.success({
            content: '审核成功',
            duration: 5000,
          })
          sheetSelect()
        } else {
          Message.warning(message)
        }
      })
    },
  })
}

//导出清单
function detailExport() {
  post({
    url: '/wms/rawyarnInventoryDetail/exportRawyarnInventories',
    data: {
      materialCode: wlCode,
      sheetId: dataList.id,
    },
    responseType: 'blob',
  }).then((res: any) => {
    filedownload(res, '盘点清单.xlsx')
  })
};

//导入差异
function detailImport() {
  if (dataList.status == 4) {
    Message.warning('此盘点单已审核，无法导入差异！')
    return
  };
  const inputEle: HTMLInputElement = document.createElement('input')
  inputEle.type = 'file'
  inputEle.id = 'fileUploadExcel'
  inputEle.accept =
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
  inputEle.addEventListener('change', async (e) => {
    const formData = new FormData()
    if (dataList.id != null) {
      formData.append('sheetId', dataList.id)
    } else {
      Message.warning('此盘点单没有盘点明细，无法导入差异对比！')
      return
    }

    if (inputEle.files !== null) {
      formData.append('file', inputEle.files[0] || '')
    } else {
      Message.warning('未选择文件！')
      return
    }
    try {
      let res: any = await post({
        url: '/wms/rawyarnInventoryDetail/importRawyarnInventories',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
          token: sessionStorage.getItem('USER-TOKEN-KEY'),
        },
      })
      if (res.code == 200) {
        Message.success('导入成功')
        detailSelect();
        sheetSelect();
        return
      }
      Message.error(res.message)
    } finally {

    }
  })
  inputEle.click()
}

// 终止盘点
function delInventories() {
  let rows = sheetGridOptions.value.getSelectedRows()
  if (rows.length === 0) {
    Message.warning('请选择要终止的盘点单！')
    return
  }
  if (rows[0].status == 3) {
    Message.warning('此数据已经审核完成，无法终止！')
    return
  }
  Modal.confirm({
    title: '系统提示',
    content: '是否终止此盘点单?',
    onOk() {
      post({
        url: '/wms/rawyarnInventoryDetail/discardInventorySheet',
        data: rows[0],
      }).then(({ data, code, message }: any) => {
        if (code === 200) {
          Message.success({
            content: '终止成功',
            duration: 5000,
          })
          sheetSelect()
        }
        else {
          Message.error({
            content: message,
            duration: 5000,
          })
        }
      })
    },
  })
}

const addHandler = () => {
  //添加新的行
  let newRows: any = {
    sheetId: dataList.id,
    companyId: sheetData.companyId,
    machineCode: '',
    materialCode: '',
    materialName: '',
    brandName: '',
    yarnBatch: '',
    colorCode: '',
    colorName: '',
    totalWeight: null,
    realWeight: null,
    diffWeight: null,
    editable: true
  };
  detailList.value.unshift(newRows);
  gridOption2.value.setRowData(detailList.value)
  console.log(detailList.value);
}
const { saveGridState:saveGridState01, updateGridState:updateGridState01 } = saveOrUpdateGridState01('WorkshopYarnInventory-1',sheetGridOptions,colState, sheetColDefs)
    const onColumnMoved = () => {
      saveGridState01()
    }
    const onColumnResized=()=>{
      saveGridState01()
    }
    const onColumnVisible=()=>{
      saveGridState01()
    }
</script>
<script lang="ts">
export default {
  name: 'ProductInStock',
}
</script>

<style scoped>.arco-select-dropdown {
  width: 150px;
}

.ag-header-cell-label {
  justify-content: center;
}</style>



